package com.yongche.utils

import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat

import scala.util.parsing.json.JSON

/**
  * Created by yd on 2016/10/13.
  */

object ArgumentParser {
  def main(args: Array[String]): Unit = {
    val json =
      """{
        |  "topic": "topic",
        |  "brokers": "brokers",
        |  "zkHost": "presto1.bi.bj2.yongche.com:2181,presto2.bi.bj2.yongche.com:2181,presto3.bi.bj2.yongche.com:2181",
        |  "slideDuration": 5,
        |  "timeField": {
        |    "index": 8,
        |    "type": "timestamp"
        |  }
        |}"""
        .stripMargin
    parse(json)
  }

  def parse(json: String) = {
    val obj = JSON.parseFull(json)
    obj match {
      case Some(mmap) =>
        val map = mmap.asInstanceOf[Map[String, Any]]
        (
          //kafka的topic
          map.get("topic").asInstanceOf[Option[String]],
          //kafak的地址
          map.get("brokers").asInstanceOf[Option[String]],
          //zookeeper的地址和端口，可以和kafka的不一致，作为kafka offset的保存
          map.get("zkHost").asInstanceOf[Option[String]],
          //滑动窗口
          map.get("slideDuration").asInstanceOf[Option[Double]].map(_.toInt),
          //时间切分的字段索引，此处默认为时间戳
          map.get("timeField").asInstanceOf[Option[Map[String, Any]]].map {
            mmap =>
              val index = mmap.get("index").asInstanceOf[Option[String]]
                .getOrElse(throw new RuntimeException("时间字段未制定")).toInt
              val tpe = mmap.get("type").asInstanceOf[Option[String]]
              //根据不同的日志格式，转成不同的转换方法
              val transferFun = tpe match {
                case Some("timestamp") => (timeStamp: String) => {
                  val dt = new DateTime(timeStamp.toLong * 1000)
                  dt.toString(TimeUtils.YYYYMMDDHH)
                }
                case Some(format) => (formatTime: String) => {
                  val dt = DateTime.parse(formatTime, DateTimeFormat.forPattern(format))
                  dt.toString(TimeUtils.YYYYMMDDHH)
                }
              }
              (index, transferFun)
          }
          )
      case None => throw new IllegalArgumentException("Json解析失败")
    }
  }
}
